import 'dart:convert';
import 'package:dio/dio.dart';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:login/config/SystemConfig.dart';
import 'package:login/util/UserInfo.dart';

class AddPage extends StatefulWidget {
  AddPage({Key key}) : super(key: key);
  @override
  _AddPageState createState() => _AddPageState();
}

class _AddPageState extends State<AddPage> {
  //用户信息对象
  Map userInfo;

  //填写的文字内容
  String _content = "";

  //图片上传后返回的服务器图片保存的路径
  String _imgUploadUrl = "";
  //选择图片对象
  File _image;
  //图片选择组件对象
  final picker = ImagePicker();

  // //File类型，用来上传图片
  // PickedFile _image;

  // //用来接受上传data
  // String _imageUrl;

  //文本控制器
  // TextEditingController _content = new TextEditingController();

  @override
  void initState() {
    super.initState();
    //初始化
    this._init();
  }

  //初始化函数
  void _init() async {
    Map tempUserInfo = await UserInfo.getUserInfo(); //获取登录用户信息
    setState(() {
      this.userInfo = tempUserInfo;
    });
  }

  Future _getImage() async {
    // 这里可以实现成一个菜单弹出选择拍照或选择相册，这里固定为相册选择
    // 拍照
    // final pickedFile = await picker.getImage(source: ImageSource.camera);
    // 相册
    final pickedFile = await picker.getImage(source: ImageSource.gallery);
    // 转换成文件对象
    File pickedImage = File(pickedFile.path);
    // 上传至服务器
    _upLoadImage(pickedImage);
    // 显示预览
    setState(() {
      _image = pickedImage;
    });
  }

  // 文件上传
  void _upLoadImage(File image) async {
    String path = image.path;
    var name = path.substring(path.lastIndexOf("/") + 1, path.length);
    var suffix = name.substring(name.lastIndexOf(".") + 1, name.length);
    FormData formData = new FormData.from({
      "file": new UploadFileInfo(new File(path), name,
          contentType: ContentType.parse("image/$suffix"))
    });

    String url = SystemConfig.BASE_URL + "/upload/upload";
    var response = await Dio().post<String>(url, data: formData);
    Map result = json.decode(response.toString());
    if (result["success"]) {
      // 保存文件上传成功后的路径
      this._imgUploadUrl = result["data"];

      Fluttertoast.showToast(
          msg: result["message"],
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER);
    } else {
      Fluttertoast.showToast(
          msg: result["message"],
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER);
    }
  }

  // 发布
  void _addContent() async {
    // 发布内容url
    String api = SystemConfig.BASE_URL + "/content/addContent";
    // 请求后台
    var response = await Dio().post(api, queryParameters: {
      "appUserId": this.userInfo["id"].toString(), //获取当前用户的手机号码
      "content": this._content, //填写的内容
      "imgUrl": this._imgUploadUrl //上传图片的url
    });
    Map result = json.decode(response.toString());
    // 判断发布成功
    if (result["success"]) {
      // 弹出发布成功提示
      Fluttertoast.showToast(
          msg: result["message"],
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER);
      // 跳转到tabs页面
      Navigator.pushReplacementNamed(context, "/tabs");
    } else {
      // 发布失败，弹出错误提示
      Fluttertoast.showToast(
          msg: result["message"],
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        //可以放很多快捷键按钮
        //代表工具栏上面支持多个按钮组件
        actions: <Widget>[
          //按钮布局 有内容和样式设置用一个container()
          Container(
            padding: EdgeInsets.all(10.0),
            width: 80.0,
            child: RaisedButton(
              onPressed: this._addContent,
              //按钮
              child: Text(
                '发布',
                style: TextStyle(color: Colors.white, fontSize: 14.0),
              ),
              color: Colors.orangeAccent, //按钮颜色
              shape: RoundedRectangleBorder(
                  //设置按钮的外型装饰
                  borderRadius: BorderRadius.circular(8), //圆角幅度
                  //无边框
                  side: BorderSide.none),
            ),
          ),
        ],
      ),
      body: Container(
        margin: EdgeInsets.all(20.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            TextField(
              //设置文本框多行
              keyboardType: TextInputType.multiline,
              //限制最大行数5行
              maxLines: 5,
              //设置光标颜色，光标默认的颜色是主题的颜色黄色
              cursorColor: Colors.orangeAccent,
              //对文本框进行装饰
              decoration: InputDecoration(
                //默认填充文本
                hintText: '这一刻的想法....',
                //不显示边框
                border: OutlineInputBorder(borderSide: BorderSide.none),
              ),
              onChanged: (value) {
                this._content = value;
              }, //文字内容改变时，会触发改变事件，会传参数
            ),
            Container(
              //有图标和按钮考虑用Inlwell
              child: _image == null
                  ? InkWell(
                      child: Container(
                        width: 120.0,
                        height: 120.0,
                        margin: EdgeInsets.only(top: 10.0, left: 10.0),
                        decoration: BoxDecoration(
                            border: Border.all(color: Colors.grey, width: 1.0)),
                        // child: Icon(Icons.add, size: 60.0, color: Colors.grey),
                        child: Icon(Icons.add, size: 60.0, color: Colors.grey),
                      ),
                      onTap: this._getImage,
                    )
                  : Container(
                      width: 120.0,
                      height: 120.0,
                      margin: EdgeInsets.only(top: 10.0, left: 10.0),
                      decoration: BoxDecoration(
                          border: Border.all(color: Colors.grey, width: 1.0)),
                      child: Image.file(_image, fit: BoxFit.cover),
                    ),
            ),
          ],
        ),
      ),
     
    );
  }
}
